<!--
  余额管理主页面
  @description 商户余额管理的列表页面，包含搜索、表格、分页、操作等功能
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <ContentWrap>
    <!-- 搜索表单 -->
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      label-width="68px"
      class="-mb-15px"
    >
      <el-form-item :label="t('settle.balance.merchantNo')" prop="merchantNo">
        <el-input
          v-model="queryParams.merchantNo"
          :placeholder="t('settle.common.pleaseInput') + t('settle.balance.merchantNo')"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('settle.balance.merchantName')" prop="merchantName">
        <el-input
          v-model="queryParams.merchantName"
          :placeholder="t('settle.common.pleaseInput') + t('settle.balance.merchantName')"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('settle.balance.balanceType')" prop="balanceType">
        <el-select
          v-model="queryParams.balanceType"
          :placeholder="t('settle.common.pleaseSelect') + t('settle.balance.balanceType')"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="(label, value) in balanceTypeOptions"
            :key="value"
            :label="label"
            :value="parseInt(value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          {{ t('settle.common.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          {{ t('settle.common.reset') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['settle:balance:export']"
        >
          <Icon class="mr-5px" icon="ep:download" />
          {{ t('settle.common.export') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" row-key="id">
      <el-table-column
        :label="t('settle.balance.merchantNo')"
        align="center"
        prop="merchantNo"
        width="180"
      />
      <el-table-column
        :label="t('settle.balance.merchantName')"
        align="center"
        prop="merchantName"
        min-width="150"
      />
      <el-table-column
        :label="t('settle.balance.balanceType')"
        align="center"
        prop="balanceType"
        width="120"
      >
        <template #default="scope">
          <el-tag :type="getBalanceTypeTagType(scope.row.balanceType)">
            {{ balanceTypeOptions[scope.row.balanceType] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.balance.availableBalance')"
        align="center"
        prop="availableBalance"
        width="140"
      >
        <template #default="scope">
          <span class="available-text">¥{{ (scope.row.availableBalance / 100).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.balance.frozenBalance')"
        align="center"
        prop="frozenBalance"
        width="120"
      >
        <template #default="scope">
          <span class="frozen-text">¥{{ (scope.row.frozenBalance / 100).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.balance.totalBalance')"
        align="center"
        prop="totalBalance"
        width="140"
      >
        <template #default="scope">
          <span class="total-text">¥{{ (scope.row.totalBalance / 100).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.common.updateTime')"
        align="center"
        prop="updateTime"
        width="180"
        :formatter="dateFormatter"
      />
      <el-table-column
        :label="t('settle.common.operation')"
        align="center"
        width="200"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openChangeRecords(scope.row)"
            v-hasPermi="['settle:balance:query']"
          >
            {{ t('settle.balance.viewRecords') }}
          </el-button>
          <el-button
            link
            type="warning"
            @click="handleFreeze(scope.row)"
            v-hasPermi="['settle:balance:freeze']"
            v-if="scope.row.availableBalance > 0"
          >
            {{ t('settle.balance.freeze') }}
          </el-button>
          <el-button
            link
            type="success"
            @click="handleUnfreeze(scope.row)"
            v-hasPermi="['settle:balance:unfreeze']"
            v-if="scope.row.frozenBalance > 0"
          >
            {{ t('settle.balance.unfreeze') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 余额变动记录 -->
  <BalanceChangeRecords ref="changeRecordsRef" />

  <!-- 冻结/解冻对话框 -->
  <FreezeBalanceDialog ref="freezeDialogRef" @success="getList" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { dateFormatter } from '@/utils/formatTime'
import { useMessage } from '@/hooks/web/useMessage'
import { getMerchantBalanceListApi, exportMerchantBalanceApi } from '@/api/settle/balance'
import type { BalanceVO, BalancePageReqVO } from '@/api/settle/types'
import { BalanceTypeEnum } from '@/api/settle/types'
import { ContentWrap } from '@/components/ContentWrap'
import { Icon } from '@/components/Icon'
import Pagination from '@/components/Pagination/index.vue'
import BalanceChangeRecords from './BalanceChangeRecords.vue'
import FreezeBalanceDialog from './FreezeBalanceDialog.vue'

defineOptions({ name: 'SettleBalance' })

const { t } = useI18n()
const message = useMessage()

// 加载状态
const loading = ref(true)
const exportLoading = ref(false)

// 列表数据
const list = ref<BalanceVO[]>([])
const total = ref(0)

// 查询参数
const queryParams = reactive<BalancePageReqVO>({
  pageNo: 1,
  pageSize: 10,
  merchantNo: undefined,
  merchantName: undefined,
  balanceType: undefined
})

// 表单引用
const queryFormRef = ref<FormInstance>()
const changeRecordsRef = ref()
const freezeDialogRef = ref()

// 选项数据
const balanceTypeOptions = {
  [BalanceTypeEnum.AVAILABLE]: t('settle.balance.balanceTypes.available'),
  [BalanceTypeEnum.FROZEN]: t('settle.balance.balanceTypes.frozen'),
  [BalanceTypeEnum.TOTAL]: t('settle.balance.balanceTypes.total')
}

/**
 * 查询列表
 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getMerchantBalanceListApi(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('查询余额列表失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/**
 * 查看余额变动记录
 */
const openChangeRecords = (row: BalanceVO) => {
  changeRecordsRef.value.open(row)
}

/**
 * 冻结余额
 */
const handleFreeze = (row: BalanceVO) => {
  freezeDialogRef.value.open(row, 'freeze')
}

/**
 * 解冻余额
 */
const handleUnfreeze = (row: BalanceVO) => {
  freezeDialogRef.value.open(row, 'unfreeze')
}

/**
 * 导出按钮操作
 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    await exportMerchantBalanceApi(queryParams)
    message.success(t('settle.common.exportSuccess'))
  } catch (error) {
    console.error('导出余额数据失败:', error)
  } finally {
    exportLoading.value = false
  }
}

// 标签类型获取函数
const getBalanceTypeTagType = (type: number) => {
  const typeMap = {
    [BalanceTypeEnum.AVAILABLE]: 'success',
    [BalanceTypeEnum.FROZEN]: 'warning',
    [BalanceTypeEnum.TOTAL]: 'primary'
  }
  return typeMap[type] || ''
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.available-text {
  color: #67c23a;
  font-weight: bold;
}

.frozen-text {
  color: #e6a23c;
  font-weight: bold;
}

.total-text {
  color: #409eff;
  font-weight: bold;
  font-size: 16px;
}
</style>
